from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.utils import simplejson
from openpolitics.feedreader.models import Log
from django.core.urlresolvers import reverse

def index(request,
          template_name='openpolitics/feedreader'):
    if not request.user.is_staff:
        return HttpResponseRedirect(reverse('openpolitics.browser.views.index'))
    return render_to_response('%s/index.html' % template_name, {
    })

def reindex(request,
          template_name='openpolitics/browser'):
    if not request.user.is_staff:
        return HttpResponseRedirect(reverse('openpolitics.browser.views.index'))
    import openpolitics.feedreader.readers.sejmgovpl.reader as reader
    reader.reload()
    return render_to_response('%s/index.html' % template_name, {
    })

def task_status(request,
                template_name='openpolitics/browser'):
    if not request.user.is_staff:
        return HttpResponseRedirect(reverse('openpolitics.browser.views.index'))
    log = Log.objects.all().order_by('-timestamp')
    if not log:
        return HttpResponse(simplejson.dumps({'status': 0}, indent=2))
    log = log[0]
    status = int(float(log.items)/float(460)*100)
    return HttpResponse(simplejson.dumps({'status': status}, indent=2))